package controllers

import (
	"database/sql"
	"encoding/json"
	"findInDatabase/comm"
	"findInDatabase/entity"
	"fmt"

	"github.com/astaxie/beego"
	_ "github.com/go-sql-driver/mysql"
)

var dbs map[string]*sql.DB

type BeginQueryController struct {
	beego.Controller
}

func (c *BeginQueryController) BeginQuery() {
	defer func() {
		err := recover()
		if nil != err {
			c.Data["json"] = map[string]interface{}{
				"status":    false,
				"errorInfo": err,
			}
			c.ServeJSON()
		}
	}()
	comm.CreateFile()
	if nil == dbs {
		dbs = make(map[string]*sql.DB)
	}
	var dbInfoMap entity.DbInfoMap
	json.Unmarshal(c.Ctx.Input.RequestBody, &dbInfoMap)
	for k, m := range dbInfoMap.DbInfo {
		beego.Info(fmt.Sprintf("连接mysql数据库 %s ...", k))
		connstr := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", m["usr"], m["pwd"], m["ip"], m["port"], m["db"])
		db, err := sql.Open("mysql", connstr)
		if nil != err {
			tempLog := fmt.Sprintf("mysql数据库 %s 连接失败", k)
			beego.Error(tempLog)
			comm.WriteFile(tempLog)
			continue
		}
		dbs[k] = db
		beego.Info(fmt.Sprintf("mysql数据库 %s 已加入连接池", k))
		rows, err := db.Query("show tables")
		defer rows.Close()
		if err != nil {
			tempLog := fmt.Sprintf("mysql数据库连接失败 %s", err)
			beego.Error(tempLog)
			comm.WriteFile(tempLog)
			continue
		}
		var tempR string
		var resultStr string
		for rows.Next() {
			err := rows.Scan(&tempR)
			if err != nil {
				beego.Error(err)
				comm.WriteFile(fmt.Sprintf("读取字段失败: %s", err))
				continue
			}
			resultStr += tempR + "\n"
		}
		beego.Info(resultStr)
	}
	c.Data["json"] = map[string]interface{}{
		"status":    true,
		"errorInfo": "test",
		"test":      dbInfoMap,
	}
	c.ServeJSON()
}
